package com.mdxl.shiro.service;

import com.mdxl.shiro.dao.UserMapper;
import com.mdxl.shiro.entity.SysPermission;
import com.mdxl.shiro.entity.SysRole;
import com.mdxl.shiro.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author:MuJiuTian
 * @Description:
 * @Date: Created in 下午10:59 2019/10/31
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    /**
     * 通过账号和密码查找user
     */
    public User getUserByPwd(String username, String pwd) {
        return new User();
    }

    /**
     * 通过账号查找user
     */
    public User findByUserName(String userName){
        return userMapper.findByUserName(userName);
    }

    /**
     * 注册
     */
    public void regist(String username,String salt,String uid){
        Map<String,Object> map = new HashMap<>(8);
        map.put("username",username);
        map.put("password",uid);
        map.put("salt",salt);
        map.put("creat", new Date());
        userMapper.regist(map);
    }

    /**
     * 登陆
     */
    public boolean login(String userName, String password){
        // 1、获取Subject实例对象
        Subject currentUser = SecurityUtils.getSubject();

        // 2、判断当前用户是否登录
        if (currentUser.isAuthenticated() == false) {
            // 2.1、进行登陆业务逻辑
        }

        // 3、将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);

        // 4、认证 传到MyAuthorizingRealm类中的方法进行认证
        currentUser.login(token);
        Session session = currentUser.getSession();
        session.setAttribute("userName", userName);

        return true;
    }

    /**
     * 退出
     */
    public void logout(){

    }

    /**
     * 获取用户的所有角色
     */
    public List<SysRole> getUserRoleList(int userId){
        return userMapper.getRoleList(userId);
    }

    /**
     * 获取角色的所有权限
     */
    public List<SysPermission> getPermissionList(int roleId){
        return userMapper.getPermissionList(roleId);
    }
}
